import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AppConfigService } from '@basic';
import { ACLService } from '@delon/acl';
import { _HttpClient, MenuService, SettingsService, TitleService } from '@delon/theme';
import { ArrayService } from '@delon/util';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzIconService } from 'ng-zorro-antd/icon';
import { catchError, map, Observable, zip } from 'rxjs';

import { ICONS } from '../../../style-icons';
import { ICONS_AUTO } from '../../../style-icons-auto';

/**
 * Used for application startup
 * Generally used to get the basic data of the application, like: Menu Data, User Data, etc.
 */
@Injectable()
export class StartupService {
    constructor(
        iconSrv: NzIconService,
        private menuService: MenuService,
        private settingService: SettingsService,
        private aclService: ACLService,
        private titleService: TitleService,
        private httpClient: _HttpClient,
        private config: AppConfigService,
        private router: Router,
        private arrSrv: ArrayService
    ) {
        iconSrv.addIcon(...ICONS_AUTO, ...ICONS);
    }

    load(): Observable<void> {
        return zip(
            this.httpClient.get('assets/config/app-data.json'),
            this.httpClient.get(`${this.config.appApiHost}/system/user/getInfo`),
            this.httpClient.get(`${this.config.appApiHost}/system/menu/getRouters`)
        ).pipe(
            // 接收其他拦截器后产生的异常消息
            catchError(res => {
                console.warn(`StartupService.load: Network request failed`, res);
                // setTimeout(() => this.router.navigateByUrl(`/exception/500`));
                return [];
            }),
            map(([appData, userInfo, routers]: [NzSafeAny, NzSafeAny, NzSafeAny]) => {
                if (!userInfo.data || !routers.data) {
                    return;
                }
                // 应用信息：包括站点名、描述、年份
                this.settingService.setApp({
                    name: 'xxxx', // 媒体投放
                    description: 'xxxx'
                });
                const _userInfo = userInfo.data.user;
                let _menuTree: any = [
                    {
                        children: routers.data
                    }
                ];
                // 用户信息：包括姓名、头像、邮箱地址
                this.settingService.setUser({
                    name: _userInfo.nickName,
                    avatar: _userInfo.avatar,
                    email: ''
                });
                // ACL：设置权限为全量
                // this.aclService.setFull(true);
                this.aclService.set({ role: userInfo.data.roles, ability: userInfo.data.permissions });
                this.arrSrv.visitTree(
                    _menuTree,
                    (item, parent, deep) => {
                        item.text = item?.meta?.title;
                        item.link = item?.component;
                        item.icon = item?.meta?.icon;
                    },
                    { childrenMapName: 'children' }
                );
                // 初始化菜单
                this.menuService.add(_menuTree);
                // 设置页面标题的后缀
                this.titleService.default = '';
                // this.titleService.suffix = appData.app.name;
            })
        );
    }
}
